<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 教师管理主页
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
<!--                <el-select v-model="query.tid" placeholder="教师编号" class="handle-select mr10">-->
<!--                    <el-option key="001" label="001" value="001"></el-option>-->
<!--                    <el-option key="002" label="002" value="002"></el-option>-->
<!--                    <el-option key="003" label="003" value="003"></el-option>-->
<!--                </el-select>-->
              <el-input v-model="query.tid" placeholder="教师编号" class="handle-input mr10"></el-input>
                <el-input v-model="query.name" placeholder="教师姓名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>

          <div class="handle-right">
             <el-button type="primary" icon="el-icon-plus" @click="createForm">增加</el-button>
          </div>

            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
                <el-table-column type="index" label="序号" width="55" align="center" :index="indexAdd"></el-table-column>
                <el-table-column prop="name" label="教师姓名" align="center"></el-table-column>
                <el-table-column prop="sex" label="性别" align="center"></el-table-column>
                <el-table-column prop="tid" label="教师编号" align="center"></el-table-column>
                <el-table-column prop="classNo" label="管理班级" align="center"></el-table-column>
                <el-table-column prop="phone" label="电话" align="center"></el-table-column>
                <el-table-column prop="post" label="职务" align="center"></el-table-column>

                <el-table-column label="操作" width="180" align="center">
                    <template #default="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.pageNum"
                    :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" v-model="editVisible" width="40%" >
            <el-form  ref="formRef" :model="form" :rules="editRules" label-width="80px">
                <el-form-item label="用户名" prop="name">
                    <el-input  v-model="form.name" type="text" placeholder="请输入用户名" ></el-input>
                </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" type="text"  placeholder="请选择">
                  <el-option key="男" label="男" value="男"></el-option>
                  <el-option key="女" label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="教师编号" prop="tid">
                <el-input v-model="form.tid" type="text" placeholder="请输入教师编号"></el-input>
              </el-form-item>
              <el-form-item label="管理班级" prop="classNo">
                <el-input v-model="form.classNo" type="text" placeholder="请输入:"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model="form.phone" type="text" placeholder="请输入:"></el-input>
              </el-form-item>
              <el-form-item label="职务" prop="post">
                <el-select v-model="form.post" placeholder="请选择">
                  <el-option key="班主任" label="班主任" value="班主任"></el-option>
                  <el-option key="辅导员" label="辅导员" value="辅导员"></el-option>
                  <el-option key="其他" label="其他" value="其他"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>


        <!-- 新建弹出框 -->
        <el-dialog title="新建" v-model="addVisible" width="40%">
            <el-form ref="formRef" :model="form" :rules="editRules" label-width="80px">
              <el-form-item label="用户名" prop="name">
                <el-input  v-model="form.name" type="text" placeholder="请输入用户名" ></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" type="text"  placeholder="请选择">
                  <el-option key="男" label="男" value="男"></el-option>
                  <el-option key="女" label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="教师编号" prop="tid">
                <el-input v-model="form.tid" type="text" placeholder="请输入教师编号"></el-input>
              </el-form-item>
              <el-form-item label="管理班级" prop="classNo">
                <el-input v-model="form.classNo" type="text" placeholder="请输入:"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model="form.phone" type="text" placeholder="请输入:"></el-input>
              </el-form-item>
              <el-form-item label="职务" prop="post">
                <el-select v-model="form.post" placeholder="请选择">
                  <el-option key="班主任" label="班主任" value="班主任"></el-option>
                  <el-option key="辅导员" label="辅导员" value="辅导员"></el-option>
                  <el-option key="其他" label="其他" value="其他"></el-option>
                </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="create">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from 'axios';
import qs from 'qs';

export default {
    name: "teacher",
    data() {
        return {
          pageParams: {
            pageNum: 1, // 查询第一页
            pageSize: 10 // 每页10条
          },
        };
    },
    setup() {

        const query = reactive({
            name: "",
            tid: "",
            pageNum: 1,
            pageSize:10
        });
        const tableData = ref([]);
        const pageTotal = ref(0);
        const result = ref();
        // 获取表格数据
        const getData = () => {
             axios.get('ks/teacher/selectAll', {
                params: {
                    pageNum: query.pageNum,
                    pageSize: query.pageSize,
                    tid:query.tid,
                    name:query.name
                }
            }).then(result => {
                tableData.value = result.data.result.list;
                 pageTotal.value = result.data.result.total || 0;
               console.log('value:', result);
                console.log('list:', result.data.result.list);
                 console.log('pageTotal:', result.data.result.total);
            }).catch(err => {
                console.error(err)
            })


        };
        getData();
        // 查询操作
        const handleSearch = () => {
            query.pageNum = 1;
            getData();
        };
        // 分页导航
        const handlePageChange = (val) => {
            query.pageNum = val;
            getData();

        };
        //序号连续
        const indexAdd = (index) => {
          //  console.log("indexAdd:index=", index);
            const page = query.pageNum // 当前页码
            const pageSize = query.pageSize // 每页条数
            return index + 1 + (page - 1) * pageSize
        }
        //监听二次删除是否确定
        const isDelete =(tid) => {
            ElMessageBox.confirm("确定要删除吗？", "提示", {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: "warning"
            }).then((result) => {
                //传入tid进行删除
                const data = {
                    tid:tid,
                }
                console.log("删除-tid = ",tid);
                axios.post('ks/teacher/deleteById',
                    qs.stringify(data),
                    {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
                ).then((result) => {
                    if(result.data.success) {
                        ElMessage.success(`删除第 ${idx + 1} 行成功`);
                    } else {
                        ElMessage.error("删除失败 :",result.data.message);
                    }
                    getData();
                });


            }).catch(() => {
                ElMessage.info({message: '已取消删除'});
                getData();
            });

        }
        // 删除操作
        const handleDelete = (index,row) => {
            idx = index;
            Object.keys(form).forEach((item) => {
                form[item] = row[item];
            });
            isDelete(form.tid);
            tableData.value.splice(index, 1);

        };

        // 表格编辑时弹窗和保存
        const editVisible = ref(false);
        const addVisible = ref(false);
        const createForm= () =>{
            addVisible.value = true;
            Object.keys(form).forEach((item) => {
                form[item] = '';
            });
        }
        const form = reactive({
            id:"",
            name: "",
            sex:"",
            tid:"",
            phone:"",
            post:"",
            classNo:""
        });
        const validatePhone = (rule, value, callback) => {
            try {
              if (!value) {
                return new Error("请输入电话号码");
              } else
              {
                const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
                const isPhone = reg.test(value);
                value = Number(value); //转换为数字
                if (typeof value === "number" && !isNaN(value)) {//判断是否为数字
                  value = value.toString(); //转换成字符串
                  if (value.length < 0 || value.length > 12 || !isPhone) { //判断是否为11位手机号
                    callback(new Error("手机号码格式如:138xxxx8754"));
                  } else {
                    callback();
                  }
                } else {
                  callback(new Error("手机号格式不对"));
                }
              }
            } catch (err) {
                this.$message.error(err.message)
            }
        };
      const checkLength = (rule, value, callback) => {
        if (value.length > 200) {
          callback(new Error('描述不能超过200字符'));
        } else {
          callback();
        }
      };

        // 定义校验规则
      const editRules = reactive({
        name: [
          { required: true, message: "用户名不能为空" , trigger: 'blur' },
          { validator: checkLength, trigger: "blur" }
        ],
        sex : [
          { required: true, message: '请选择', trigger: 'blur' }
        ],
        tid: [
          { required: true, message: '教师编号不能为空', trigger: 'blur' },
          { validator: checkLength, trigger: "blur" }
        ],
        phone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: validatePhone, trigger: "blur" }
        ],
        post: [
          { required: true, message: '请选择', trigger: 'blur' }
        ]
      })

        let idx = -1;
        const handleEdit = (index, row) => {
            idx = index;
            Object.keys(form).forEach((item) => {
                form[item] = row[item];
            });
            editVisible.value = true;
        };
        //todo
        const formRef = ref(null);
        const saveEdit = () => {
          //表单校验
          console.log("form为:",form)
              formRef.value.validate((valid) => {
                  if (valid) {
                      console.log("编辑--表单校验:",form);
                      axios.post('ks/teacher/update', form)
                          .then((result)=>{
                                  editVisible.value = false;
                                  if(result.data.success) {
                                      ElMessage.success(`修改第 ${idx + 1} 行成功`);
                                  } else {
                                      ElMessage.error(result.data.message+': 教师编号已存在 或 数据格式不正确');
                                  }
                              getData();
                              }
                          )
                  } else {
                      ElMessage.error("提交失败");
                    getData();
                  }
          });
            Object.keys(form).forEach((item) => {
                tableData.value[idx][item] = form[item];
            });

        };

        const create = () => {
          formRef.value.validate((valid) => {
            if (valid) {
              console.log("新增--表单校验:", form);
              axios.post('ks/teacher/save', form)
                  .then((result) => {
                        addVisible.value = false;
                        if (result.data.success) {
                          ElMessage.success(`添加成功`);
                        } else {
                          ElMessage.error(result.data.message + ': 教师编号已存在或数据格式不正确');
                        }
                      getData();
                      }
                  )
            } else {
              ElMessage.error("提交失败");
                getData();
            }
          });
          Object.keys(form).forEach((item) => {
            tableData.value[idx][item] = form[item];
          });
        };


        return {
            query,
            tableData,
            pageTotal,
            editVisible,
            form,
            editRules,
            addVisible,
            formRef,
            result,
            checkLength,
            isDelete,
            validatePhone,
            createForm,
            handleSearch,
            handlePageChange,
            handleDelete,
            handleEdit,
            saveEdit,
            create,
            indexAdd
        };
    },
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}
.handle-right {
  margin-bottom: 20px;
  float:right;
}
.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
